<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
* STATISTICS class
*
*****/
class STATISTICS
{
// Constructor
	function STATISTICS($db, $vars)
	{
		$this->db = $db;
		$this->vars = $vars;
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/messages/SUCCESS.php");
		$this->success = new SUCCESS();
		include_once("core/html/MISC.php");
		include_once("core/html/TABLE.php");
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
	}
// check we are allowed toview statistics
	function gateKeep($method)
	{
		if(!$this->session->getVar("setup_write"))
		{
			include_once("core/authorize/AUTHORIZE.php");
			$authorize = new AUTHORIZE($this->db);
			return $authorize->initLogon();
		}
		return $this->$method();
	}
	function display()
	{
		include_once("core/resource/RESOURCEMAP.php");
		$this->resourceMap = new RESOURCEMAP();
		$this->template->setVar('heading', $this->messages->text("heading", "statistics"));
		$pString = $this->totals();
		$pString .= $this->resourceAccesses();
		$pString .= $this->resourceDates();
		$pString .= $this->userData();
		$pString .= $this->resourceTypes();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}
	function totals()
	{
		$recordSet = $this->db->select(array("WKX_database_summary"), array('totalResources', 'totalQuotes', 
			'totalParaphrases', 'totalMusings'));
		$row = $this->db->fetchRow($recordSet);
		$this->totalResources = $row['totalResources'];
		$string = MISC::br() . $this->messages->text("statistics", "totalResources") . 
			"&nbsp;&nbsp;" . MISC::i($this->totalResources);
		$string .= MISC::br() . $this->messages->text("statistics", "totalQuotes") . 
			"&nbsp;&nbsp;" . MISC::i($row['totalQuotes']);
		$string .= MISC::br() . $this->messages->text("statistics", "totalParaphrases") . 
			"&nbsp;&nbsp;" . MISC::i($row['totalParaphrases']);
		$string .= MISC::br() . $this->messages->text("statistics", "totalMusings") . 
			"&nbsp;&nbsp;" . MISC::i($row['totalMusings']);
		return MISC::p($string);
	}
	function resourceAccesses()
	{
		$recordSet = $this->db->selectMax(array("WKX_resource_misc"), 'accesses');
		$row = $this->db->fetchRow($recordSet);
		$string = $this->messages->text("statistics", "maxAccesses") . 
			"&nbsp;&nbsp;" . MISC::i($row['accesses']);
		$recordSet = $this->db->selectMin(array("WKX_resource_misc"), 'accesses');
		$row = $this->db->fetchRow($recordSet);
		$string .= MISC::br() . $this->messages->text("statistics", "minAccesses") . 
			"&nbsp;&nbsp;" . MISC::i($row['accesses']);
		return MISC::p($string);
	}
	function resourceDates()
	{
		$recordSet = $this->db->selectMin(array("WKX_resource_timestamp"), 'timestampAdd');
		$row = $this->db->fetchRow($recordSet);
		$string = $this->messages->text("statistics", "firstAdded") . 
			"&nbsp;&nbsp;" . MISC::i($row['timestampAdd']);
		$recordSet = $this->db->selectMax(array("WKX_resource_timestamp"), 'timestampAdd');
		$row = $this->db->fetchRow($recordSet);
		$string .= MISC::br() . $this->messages->text("statistics", "lastAdded") . 
			"&nbsp;&nbsp;" . MISC::i($row['timestampAdd']);
		$recordSet = $this->db->selectAverageDate(array("WKX_resource_timestamp"), 'timestampAdd');
		$average = $this->db->fetchOne($recordSet);
		$string .= MISC::br() . $this->messages->text("statistics", "meanAddedResource") . 
			"&nbsp;&nbsp;" . MISC::i($average);
		return MISC::p($string);
	}
	function userData()
	{
		$recordSet = $this->db->selectCountMax(array("WKX_resource_misc"), 'addUserIdResource');
		$row = $this->db->fetchRow($recordSet);
		$user = MISC::a('link', $this->getUsername($row['addUserIdResource']), 
			"index.php?action=selectProcess" . htmlentities("&statistics=resourceUser&id=" . 
			$row['addUserIdResource']));
		$string = $this->messages->text("statistics", "userResourceTotal") . 
			"&nbsp;&nbsp;" . MISC::i($row['count'] . "&nbsp;($user)");
		$recordSet = $this->db->selectCountMax(array("WKX_resource_quote_text"), 'addUserIdQuote');
		$row = $this->db->fetchRow($recordSet);
		if($row['count'])
		{
			$user = MISC::a('link', $this->getUsername($row['addUserIdQuote']), 
				"index.php?action=selectProcess" . htmlentities("&statistics=quoteUser&id=" . 
				$row['addUserIdQuote']));
			$string .= MISC::br() . $this->messages->text("statistics", "userQuoteTotal") . 
				"&nbsp;&nbsp;" . MISC::i($row['count'] . "&nbsp;($user)");
		}
		$recordSet = $this->db->selectCountMax(array("WKX_resource_paraphrase_text"), 'addUserIdParaphrase');
		$row = $this->db->fetchRow($recordSet);
		if($row['count'])
		{
			$user = MISC::a('link', $this->getUsername($row['addUserIdParaphrase']), 
				"index.php?action=selectProcess" . htmlentities("&statistics=paraphraseUser&id=" . 
				$row['addUserIdParaphrase']));
			$string .= MISC::br() . $this->messages->text("statistics", "userParaphraseTotal") . 
				"&nbsp;&nbsp;" . MISC::i($row['count'] . "&nbsp;($user)");
		}
		$recordSet = $this->db->selectCountMax(array("WKX_resource_musing_text"), 'addUserIdMusing');
		$row = $this->db->fetchRow($recordSet);
		if($row['count'])
		{
			$user = MISC::a('link', $this->getUsername($row['addUserIdMusing']), 
				"index.php?action=selectProcess" . htmlentities("&statistics=musingUser&id=" . 
				$row['addUserIdMusing']));
			$string .= MISC::br() . $this->messages->text("statistics", "userMusingTotal") . 
				"&nbsp;&nbsp;" . MISC::i($row['count'] . "&nbsp;($user)");
		}
		return MISC::p($string);
	}
	function getUsername($id)
	{
		$recordset = $this->db->select(array('WKX_users'), array('username', 'fullname', 'id'), 
			" WHERE " . $this->db->formatField('id') . "=" . $this->db->tidyInput($id));
		$row = $this->db->fetchRow($recordset);
		if($row['fullname'])
			return $row['fullname'];
		else if($row['username'])
			return $row['username'];
		else
			return $this->messages->text("user", "unknown");
	}
	function resourceTypes()
	{
		$pString = MISC::b($this->messages->text("statistics", "resourceTypes"));
		$pString .= TABLE::tableStart(FALSE, 0, 0, 0, "left");
		$recordSet = $this->db->selectCounts(array("WKX_resource"), 'type', 'DESC');
		$maxNo = FALSE;
		while($row = $this->db->loopRecordSet($recordSet))
		{
			if(!$maxNo)
				$maxNo = $row['count']; // first in row ordered DESC
			$pString .= TABLE::trStart();
//			$pString .= TABLE::td($this->messages->text("resourceType", $row['type']));
			$pString .= TABLE::td(MISC::a('link', $this->messages->text("resourceType", $row['type']), 
				"index.php?action=selectProcess" . htmlentities("&statistics=type&id=" . 
				$row['type'])));
// 100% width of bar == arbitrary 500 px
			$percentage = round((($row['count'] / $this->totalResources) * 100), 1);
			$width = round((($row['count'] / $maxNo) * 500), 0);
			$bar = MISC::img("core/statistics/green.gif", $width, 15, $row['type']);
			$pString .= TABLE::td($bar . MISC::i("&nbsp;&nbsp;" . $row['count'] . "&nbsp;($percentage%)"));
			$pString .= TABLE::trEnd();
		}
		$pString .= TABLE::trEnd();
		$pString .= TABLE::tableEnd();
		return $pString;
	}
/***********************************************
These functions handle popularity and maturity indices and counts
***********************************************/

// Get the maximum no. access for any one resource
	function getMaxAccesses()
	{
		$this->maxAccesses = $this->db->fetchOne(($this->db->selectMax(array("WKX_resource_misc"), 'accesses')));
	}

// Return the popularity index for a resource
	function getPopularityIndex($accesses)
	{
		if(!isset($this->maxAccesses))
			$this->getMaxAccesses();
		return round(($accesses / $this->maxAccesses) * 100, 2);
	}
// Set the maturity index for a resource
	function setMaturityIndex()
	{
		if(!$this->session->getVar("setup_superadmin"))
			return $this->badInput($this->errors->text("inputError", "invalid"));
		if(!array_key_exists('resourceId', $this->vars) || !array_key_exists('maturityIndex', $this->vars) || 
		!is_numeric($this->vars['maturityIndex']))
			return $this->badInput($this->errors->text("inputError", "invalid"));
		$mIndex = round(trim($this->vars['maturityIndex']), 1);
		if($mIndex > 10)
			$mIndex = 10;
		else if($mIndex < 0)
			$mIndex = 0;
		$this->db->updateSingle('WKX_resource_misc', 
			$this->db->formatField('maturityIndex') .  "=" . $this->db->tidyInput($mIndex), 
			" WHERE " . $this->db->formatField('id') . '=' . $this->db->tidyInput($this->vars['resourceId']));
		include_once("core/resource/RESOURCEVIEW.php");
		$resource = new RESOURCEVIEW($this->db, $this->vars);
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $resource->view($this->success->text("maturityIndex"), 'lastSolo'));
	}
// Error handling - send them back to view a resource.
	function badInput($error)
	{
		include_once("core/resource/RESOURCEVIEW.php");
		$resource = new RESOURCEVIEW($this->db, $this->vars);
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $resource->view($error, 'lastSolo'));
	}
}
?>
